package com.xxh.securitydemo.compoent;

import cn.hutool.core.collection.CollUtil;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.Iterator;

/**
 * 决策用户是否有权限访问资源
 */
@ConditionalOnBean(name = "dynamicSecurityService")
@Component
public class DynamicAccessDecisionManager implements AccessDecisionManager {

    //重点重写decide方法
    @Override
    public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {

        //要是路径没有设置访问权限就可以直接放行
        if(CollUtil.isEmpty(configAttributes)){
            return;
        }
        Iterator<ConfigAttribute> iterator = configAttributes.iterator();
        while (iterator.hasNext()){
            ConfigAttribute attribute = iterator.next();
            //访问该路径需要的权限
            String needAuth = attribute.getAttribute();
            //获取用户具有的资源权限
            for (GrantedAuthority grantedAuthority:authentication.getAuthorities()){
                if(grantedAuthority.getAuthority().trim().equals(needAuth.trim())){
                    return;
                }
            }
        }
        //要是不存在权限，就返回异常
        throw new AccessDeniedException("权限不足");
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return true;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
